import { _decorator, Component, instantiate, Prefab } from 'cc';
// import { GamerInfo, UserType } from '../main/lib/StorageInfo';
const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {
  @property({ group: { name: 'Home|個人主頁|設置|规则|福利|签到|救济金|幸运抽奖', id: 'prefab1' }, type: [Prefab] })
  Chilren_Prefab: Prefab[] = new Array(6);
  @property({ group: { name: '經典模式|不换牌|排位|賽事|組隊', id: 'prefab2' }, type: [Prefab] })
  Chilren_Prefab1: Prefab[] = new Array(5);
  @property({ group: { name: '排行榜|郵件|任務|背包|商城', id: 'prefab3' }, type: [Prefab] })
  Chilren_Prefab2: Prefab[] = new Array(5);
  /**所有預製體的map容器類 */
  Prefab_Map: Map<string, Prefab> = new Map();
  static I: Main = null;

  start() {
    //把所有的prefab放到一個map對象裏
    const prefabArr = [...this.Chilren_Prefab, ...this.Chilren_Prefab1, ...this.Chilren_Prefab2];
    prefabArr.forEach(prefab => {
      if (prefab !== null) {
        this.Prefab_Map.set(prefab.name, prefab);
      }
    });
    // console.log('玩家数据', new GamerInfo(UserType.Gamer).getData());
    Main.I = this;
    Main.ToggleUI("Home");
    // Main.ToggleUI("Rules")
  }

  /**
   * UI界面祖转跳
   * @param showui 要显示的ui
   * @param hideui 要隐藏的ui
   * @param destroy 隐藏的ui是否销毁方式隐藏
   */
  static ToggleUI(showui: string, hideui?: string, destroy: boolean = true) {
    const node = Main.I.node.getChildByName(showui);//查找Main场景下名称为showui的子节点
    if (node === null) {//没有就从预制体里面加载添加
      const prefab = Main.I.Prefab_Map.get(showui);//prefab_Map里找名称showui的预制体
      if (prefab !== undefined) {
        Main.I.node.addChild(instantiate(prefab));//prefab实例化添加到Main上面
        this.HideUI(hideui, destroy);
      } else {
        console.log(`没找到${showui}该预制体资源`);
      }
    } else {
      node.active = true;
      this.HideUI(hideui, destroy);
    }
  }


  /**
   * 隐藏或者销毁指定ui
   * @param hideui 隐藏UI的name
   * @param destroy 是否以销毁的形式隐藏
   */
  private static HideUI(hideui: string, destroy: boolean) {
    const of_node = Main.I.node.getChildByName(hideui);//找到hideui名称的子节点
    if (of_node !== null) {
      //ture 就销毁当前节点 false 就隐藏节点
      destroy ? of_node.removeFromParent() : of_node.active = false;
    }
  }
}